#ifndef PBR_FUNCTIONS  
#define PBR_FUNCTIONS  

#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"


//正态分布函数D
float Distribution(float roughness2 , float nh)
{
    float lerpSquareRoughness = pow(lerp(0.002, 1, roughness2), 2);
    float D = lerpSquareRoughness / (pow((pow(nh, 2) * (lerpSquareRoughness - 1) + 1), 2) * PI);
    return D;
}

//几何遮蔽G
float Geometry(float roughness2 , float nl , float nv)
{
    float kInDirectLight = pow(roughness2 + 1, 2) / 8;
    float kInIBL = pow(roughness2, 2) / 8;
    float GLeft = nl / lerp(nl, 1, kInDirectLight);
    float GRight = nv / lerp(nv, 1, kInDirectLight);
    float G = GLeft * GRight;
    return G;
}

//菲尼尔Fresnel
float3 FresnelEquation(float3 F0 , float vh)
{
    float3 F = F0 + (1 - F0) * exp2((-5.55473 * vh - 6.98316) * vh);
    return F;
}

//立方体贴图的Mip等级计算
float CubeMapMip(float _Roughness)
{
    //基于粗糙度计算CubeMap的Mip等级
    float mip_roughness = _Roughness * (1.7 - 0.7 * _Roughness);
    float mip = mip_roughness * UNITY_SPECCUBE_LOD_STEPS; 
    return mip;
}

//间接光的菲涅尔系数
float3 fresnelSchlickRoughness(float cosTheta, float3 F0, float roughness2)
{
    return F0 + (max(float3(1 ,1, 1) * (1 - roughness2), F0) - F0) * pow(1.0 - cosTheta, 5.0);
}


float CustomDistanceAttenuation(float distanceSqr, half2 distanceAttenuation)
{
    float lightAtten = rcp(distanceSqr);//求倒数，距离越小，数组越大
    float2 distanceAttenuationFloat = float2(distanceAttenuation);

    // Use the smoothing factor also used in the Unity lightmapper.
    half factor = half(distanceSqr * distanceAttenuationFloat.x);
    half smoothFactor = saturate(half(1.0) - factor * factor);
    smoothFactor = smoothFactor * smoothFactor;
    
    return lightAtten * smoothFactor;
}

#endif /* PBR_FUNCTIONS   */
